import pygame
from math import ceil, floor
from const import *


# 判断方块是否可以移动，即移动后不与墙壁和沉底方块相碰
def movable(x, y, rock_kind, wall_yx: dict, frozen_rock_yx: dict):
    rock_sz = ROCK_SZ

    # 单个方块的判断
    def single(x1, y1):
        y_up = ceil(y1 / rock_sz) * rock_sz
        y_down = floor(y1 / rock_sz) * rock_sz
        if x1 not in wall_yx.get(y_up, []) + wall_yx.get(y_down, []) + frozen_rock_yx.get(y_up, []) \
                + frozen_rock_yx.get(y_down, []):
            return True
        return False

    lr, lc = len(rock_kind), len(rock_kind[0])
    for i in range(lr):
        for j in range(lc):
            if rock_kind[i][j] and not single(x + j * rock_sz, y + i * rock_sz):
                return False
    return True


# 沉底方块
def freeze_rock(x, y, rock_kind, frozen_rock_yx: dict):
    rock_sz = ROCK_SZ
    lr, lc = len(rock_kind), len(rock_kind[0])
    for i in range(lr):
        for j in range(lc):
            if rock_kind[i][j]:
                x1 = x + j * rock_sz
                y1 = y + i * rock_sz
                if frozen_rock_yx.get(y1):
                    frozen_rock_yx[y1].append(x1)
                else:
                    frozen_rock_yx[y1] = [x1]
    return frozen_rock_yx


# 消行
def remove_lines(frozen_rock_yx, full_lines):
    rock_sz = ROCK_SZ
    for i, (k, v) in enumerate(full_lines):
        k += i * rock_sz
        temp_dict = dict()
        frozen_rock_yx.pop(k)
        for y, x in frozen_rock_yx.items():
            if y < k:
                temp_dict[y + rock_sz] = x
            else:
                temp_dict[y] = x
        frozen_rock_yx = temp_dict
    return frozen_rock_yx


# 以扩散的形式加载图片
def fancy_load_img(screen,imx,imy,img_path,rate=1):
    if imx < 10*ROCK_SZ:
        imx += ROCK_SZ//rate
    if imy < HEIGHT-ROCK_SZ:
        imy += 2*ROCK_SZ//rate
    image = pygame.image.load(img_path)
    image = pygame.transform.scale(image, (imx, imy))
    screen.blit(image, (6*ROCK_SZ - imx // 2, (HEIGHT-ROCK_SZ)//2 - imy // 2))
    pygame.display.update()
    return imx,imy


# 显示提示文字、难度等级
def prompt_text_display(screen):
    font = pygame.font.SysFont('SimHei', 16)
    text = font.render('按空格键开始/暂停', True, Color.white.value)
    screen.blit(text, PROMPT_TEXT1_POS)
    text = font.render('按a/d键左右移动', True, Color.white.value)
    screen.blit(text, PROMPT_TEXT2_POS)
    text = font.render('按s键加速下落', True, Color.white.value)
    screen.blit(text, PROMPT_TEXT3_POS)
    text = font.render('按w键旋转方块', True, Color.white.value)
    screen.blit(text, PROMPT_TEXT4_POS)
    text = font.render('按上下箭头调节难度等级', True, Color.white.value)
    screen.blit(text, PROMPT_TEXT5_POS)
    text = font.render('当前等级:', True, Color.white.value)
    screen.blit(text, LEVEL_TEXT1_POS)
    text = font.render('历史最高:', True, Color.white.value)
    screen.blit(text, RECORD_TEXT1_POS)